﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Forums.Domain
{
	using System.Collections.Generic;
	using System.Linq;
	using Falcon.Core.Extensions;

	public class ForumAnnouncementGrouped
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="ForumAnnouncementGrouped"/> class.
		/// </summary>
		/// <param name="announcements">The announcements.</param>
		/// <param name="forums">The forums.</param>
		public ForumAnnouncementGrouped(IList<ForumAnnouncement> announcements, IList<Forum> forums)
		{
			// announcements that are not assigned to any forum
			this.Announcements = announcements.Where(x => x.ForumId == 0).ToList();

			// announcements that are assigned to a specific forum
			this.AnnouncementsBasedOnForums(announcements, forums);

			// finally add the forums
			this.Forums = forums;
		}

		/// <summary>
		/// Gets or sets the announcements.
		/// </summary>
		/// <value>The announcements.</value>
		public IList<ForumAnnouncement> Announcements
		{
			get; 
			set;
		}

		/// <summary>
		/// Gets or sets the forums.
		/// </summary>
		/// <value>The forums.</value>
		public IList<Forum> Forums
		{
			get; 
			set;
		}

		/// <summary>
		/// Populates the forums with annoucements based on if the annoucements are assigned to that forum.
		/// </summary>
		/// <param name="announcements">The announcements.</param>
		/// <param name="forums">The forums.</param>
		public void AnnouncementsBasedOnForums(IList<ForumAnnouncement> announcements, IList<Forum> forums)
		{
			foreach (var forum in forums)
			{
				var item = forum;

				forum.Announcements = announcements.Where(c => c.ForumId == item.Id).ToList();

				if (item.Childern.HasValue())
				{
					AnnouncementsBasedOnForums(announcements, item.Childern);
				}
			}
		}
	}
}